package cn.itsource.template;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itsource.constants.Constants;
import cn.itsource.constants.GlobalExceptionCode;
import cn.itsource.pojo.properties.AppSettingProperties;
import cn.itsource.pojo.properties.dto.CodeToDto;
import cn.itsource.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;

public class WeChatTemplate {
    @Autowired
    private AppSettingProperties appSettingProperties;
    public String getOpenId(String openIdCode ){
        String userUrl = String.format(Constants.Url.WX_OPENIDCODE_URL, appSettingProperties.getAppId(), appSettingProperties.getSecret(), openIdCode);
        String jsonResult = HttpUtil.get(userUrl);
        CodeToDto CodeToDto = JSONUtil.toBean(jsonResult, CodeToDto.class);
        String openid = CodeToDto.getOpenid();
        AssertUtil.isNotNull(openid,GlobalExceptionCode.PARAM_CODE_ERROR);
        return openid;
    }

    public String getPhoneNumber(String phoneCode){
//        获取accessToken
        String accessTokenUrl = String.format(Constants.Url.WX_ACCESS_TOKEN_URL, appSettingProperties.getAppId(), appSettingProperties.getSecret());
        String accessTokenStr = HttpUtil.get(accessTokenUrl);
        JSONObject jsonObject = JSONUtil.parseObj(accessTokenStr);
        String accessToken = jsonObject.getStr("access_token");
        AssertUtil.isNotNull(accessToken,GlobalExceptionCode.PARAM_CODE_ERROR);
//        获取手机号
        String getPhone = String.format(Constants.Url.WX_GET_PHONE_URL, accessToken);
        JSONObject paramJsonObj = JSONUtil.createObj();
        paramJsonObj.set("code",phoneCode);
        String phoneJsonStr = HttpUtil.post(getPhone, JSONUtil.toJsonStr(paramJsonObj));
        JSONObject jsonObject1 = JSONUtil.parseObj(phoneJsonStr);
        Integer errcode = jsonObject1.getInt("errcode");
        AssertUtil.isEquals(0,errcode,GlobalExceptionCode.PARAM_CODE_ERROR);

        JSONObject phoneInfo = jsonObject1.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getStr("phoneNumber");
        AssertUtil.isNotNull(phoneNumber, GlobalExceptionCode.PARAM_CODE_ERROR);
        return phoneNumber;
    }
}
